package com.ui.home.view;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.base.BaseSlideOutActivity;
import com.bean.SearchListBean;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.constant.Constant;
import com.ddd.wandemo.ArticleDetailWebView2;
import com.ddd.wandemo.R;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ui.home.adapter.HotKeyRvAdapter;
import com.ui.home.adapter.SearchHistoryAdapter;
import com.ui.home.adapter.SearchResultRvAdapter;
import com.ui.home.presenter.SearchActivityContract;
import com.ui.home.presenter.SearchActivityPresenter;
import com.util.SpUtil;
import com.util.ToastUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

public class SearchActivity extends BaseSlideOutActivity<SearchActivityPresenter> implements SearchActivityContract.View {

    private RecyclerView mRvHotKey;
    private HotKeyRvAdapter mHotKeyRvAdapter;
    private ImageView mIvSearchBack;
    private EditText mEtSearch;
    private String mSearchText;
    private ImageView mIvDoSearch;
    private ImageView mIvClean;
    private int searchPage = 0;
    private List<String> historyList = new ArrayList<>();
    private List<SearchListBean.DatasBean> datas = new ArrayList<>();
    private Gson mGson;


    private LinearLayout mLlHistory;
    private RecyclerView mRvHistory;
    private SearchHistoryAdapter mHistoryAdapter;
    private TextView mCleanHistory;
    private RecyclerView mSearchResult;
    private SearchResultRvAdapter mSearchResultRvAdapter;
    private LinearLayout mLlTotalHistory;
    private SwipeRefreshLayout mSrlSearch;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        mRvHotKey = findViewById(R.id.rv_hot_key);
        mIvSearchBack = findViewById(R.id.iv_search_back);
        mEtSearch = findViewById(R.id.et_search);
        mIvDoSearch = findViewById(R.id.iv_do_search);
        mIvClean = findViewById(R.id.iv_clean_search);
        mLlHistory = findViewById(R.id.ll_search_history);
        mRvHistory = findViewById(R.id.rv_search_history);
        mSearchResult = findViewById(R.id.rv_search_result);
        mCleanHistory = findViewById(R.id.tv_clean_history);
        mLlTotalHistory = findViewById(R.id.ll_total_history);
        mSrlSearch = findViewById(R.id.srl_search);


        mHotKeyRvAdapter = new HotKeyRvAdapter(this);
        mHistoryAdapter = new SearchHistoryAdapter(this);
        mSearchResultRvAdapter = new SearchResultRvAdapter(datas);

        mSrlSearch.setColorSchemeColors(mAccentColor);
        initRvAndAdapter();

    }

    private void initRvAndAdapter() {
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setAlignItems(AlignItems.STRETCH);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);

        FlexboxLayoutManager historyManager = new FlexboxLayoutManager(this);
        historyManager.setFlexWrap(FlexWrap.WRAP);
        historyManager.setFlexDirection(FlexDirection.ROW);
        historyManager.setAlignItems(AlignItems.STRETCH);
        historyManager.setJustifyContent(JustifyContent.FLEX_START);

        mRvHotKey.setLayoutManager(layoutManager);
        mRvHotKey.setAdapter(mHotKeyRvAdapter);

        mRvHistory.setLayoutManager(historyManager);
        mRvHistory.setAdapter(mHistoryAdapter);

        mSearchResult.setLayoutManager(new LinearLayoutManager(this));
        mSearchResult.setAdapter(mSearchResultRvAdapter);

    }
    @Override
    protected void initEvent() {
        mGson = new Gson();
        String history = SpUtil.getString(Constant.SP_KEY);
        //显示历史
        getSearchHistory(history);

        mPresenter.getHotKey();

        //edittext输入监听
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    mIvClean.setVisibility(View.VISIBLE);
                } else {
                    mIvClean.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

        //监听键盘搜索键
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    mSearchText = mEtSearch.getText().toString().trim();
                    if (!TextUtils.isEmpty(mSearchText)) {
                        // TODO: 2018/10/31 doSearch
                        mPresenter.getSearchList(searchPage,mSearchText);
                        saveHistory(mSearchText);
                    } else {
                        ToastUtil.showShort(SearchActivity.this,"搜索内容不能为空");
                    }
                }
                return false;
            }
        });


        mIvDoSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchText = mEtSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(mSearchText)) {
                    // TODO: 2018/10/31 doSearch
                    mPresenter.getSearchList(searchPage,mSearchText);
                    saveHistory(mSearchText);
                    hideKeyboard();
                } else {
                    ToastUtil.showShort(SearchActivity.this,"搜索内容不能为空");
                }
            }
        });

        //清空搜索框
        mIvClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtSearch.setText("");
//                if (datas.size()>0) {
//                    datas.clear();
//                    mSearchResultRvAdapter.setNewData(datas);
//                }
                searchPage = 0;
                mLlTotalHistory.setVisibility(View.VISIBLE);
                mSrlSearch.setVisibility(View.GONE);
            }
        });


        //清除搜索历史
        mCleanHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                historyList.clear();
                mHistoryAdapter.setData(historyList);
                SpUtil.setString(Constant.SP_KEY, mGson.toJson(historyList));
                mLlHistory.setVisibility(View.GONE);
            }
        });

        mIvSearchBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchActivity.this.finish();
            }
        });

        //刷新监听
        mSrlSearch.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                searchPage = 0;
                mPresenter.getSearchList(searchPage,mSearchText);
            }
        });


        mSearchResultRvAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPresenter.getSearchList(++searchPage,mSearchText);
            }
        },mSearchResult);



        //热搜item点击
        mHotKeyRvAdapter.setOnItemClickListener(new HotKeyRvAdapter.OnItemClickListener() {
            @Override
            public void itemClick(String key) {
                mSearchText = key;
                mEtSearch.setText(key);
                mPresenter.getSearchList(searchPage,mSearchText);
                saveHistory(key);
            }
        });
        //历史item点击
        mHistoryAdapter.setOnItemClickListener(new HotKeyRvAdapter.OnItemClickListener() {
            @Override
            public void itemClick(String key) {
                mSearchText = key;
                mEtSearch.setText(key);
                mPresenter.getSearchList(searchPage,mSearchText);
            }
        });

        //结果item点击
        mSearchResultRvAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SearchListBean.DatasBean data = (SearchListBean.DatasBean) adapter.getData().get(position);
                Intent intent = new Intent(SearchActivity.this, ArticleDetailWebView2.class);
                intent.putExtra("link",data.getLink());
                intent.putExtra("title",data.getTitle());
                intent.putExtra("type",ArticleDetailWebView2.TYPE_ARTICLE);
                startActivity(intent);
            }
        });
    }

    private void getSearchHistory(String historyJson) {
        //显示搜索记录
        if (TextUtils.isEmpty(historyJson)) {
            return;
        }
        historyList = mGson.fromJson(historyJson, new TypeToken<List<String>>() {}.getType());
        if (historyList != null && historyList.size()>0) {
            mLlHistory.setVisibility(View.VISIBLE);
            mHistoryAdapter.setData(historyList);
        } else {
            mLlHistory.setVisibility(View.GONE);
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0,0);
    }

    @Override
    protected SearchActivityPresenter initPresenter() {
        return new SearchActivityPresenter();
    }

    @Override
    public void onGetHotKey(List<String> keyList) {
        showHotKey(keyList);
    }

    @Override
    public void onGetSearchList(List<SearchListBean.DatasBean> datas) {
        mLlTotalHistory.setVisibility(View.GONE);
        mSrlSearch.setVisibility(View.VISIBLE);
        mSearchResultRvAdapter.setNewData(datas);
        //首次进入不走loadmore回调
        mSearchResultRvAdapter.disableLoadMoreIfNotFullPage();
        mSearchResult.scrollToPosition(0);
        mSrlSearch.setRefreshing(false);
    }

    @Override
    public void onLoadMoreSearch(List<SearchListBean.DatasBean> datas) {
        if (datas.size() == 0) {
            mSearchResultRvAdapter.loadMoreEnd();
        } else {
            mSearchResultRvAdapter.addData(datas);
            mSearchResultRvAdapter.loadMoreComplete();
        }
    }

    private void showHotKey(List<String> keyList) {
        mHotKeyRvAdapter.setData(keyList);
    }

    public void saveHistory(String history){
        if (mGson == null) {
            mGson = new Gson();
        }
        if (!TextUtils.isEmpty(history)) {
            historyList.add(history);

            //去重
            HashSet<String> set = new HashSet<>(historyList);
            historyList.clear();
            historyList.addAll(set);

            mLlHistory.setVisibility(View.VISIBLE);
            Collections.reverse(historyList);
            SpUtil.setString(Constant.SP_KEY, mGson.toJson(historyList));
            mHistoryAdapter.setData(historyList);
        }
    }
    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                    0);
        }
    }
}
